<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="hello,test,abc," />










<meta name="description" content="这是本文章的摘要信息.">
<meta name="keywords" content="hello,test,abc">
<meta property="og:type" content="article">
<meta property="og:title" content="我的文档">
<meta property="og:url" content="https://zhaoyongcnsx.github.io/2018/09/22/我的文档/index.html">
<meta property="og:site_name" content="zhaoyongCNSX Blogs">
<meta property="og:description" content="这是本文章的摘要信息.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://zhaoyongcnsx.github.io/res/mdImg/IO操作类图.png">
<meta property="og:updated_time" content="2018-09-23T11:58:04.517Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="我的文档">
<meta name="twitter:description" content="这是本文章的摘要信息.">
<meta name="twitter:image" content="https://zhaoyongcnsx.github.io/res/mdImg/IO操作类图.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zhaoyongcnsx.github.io/2018/09/22/我的文档/"/>





  <title>我的文档 | zhaoyongCNSX Blogs</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">zhaoyongCNSX Blogs</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zhaoyongcnsx.github.io/2018/09/22/我的文档/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="zhaoyongCNSX">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/logo.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zhaoyongCNSX Blogs">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">我的文档</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-09-22T11:34:53+08:00">
                2018-09-22
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-09-23T19:58:04+08:00">
                2018-09-23
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/programming/" itemprop="url" rel="index">
                    <span itemprop="name">编程</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/programming/C/" itemprop="url" rel="index">
                    <span itemprop="name">C++</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2018/09/22/我的文档/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2018/09/22/我的文档/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/2018/09/22/我的文档/" class="leancloud_visitors" data-flag-title="我的文档">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.6k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  18
                </span>
              
            </div>
          

          
              <div class="post-description">
                  这是本文章的摘要信息.
              </div>
          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <!-- RES -->
<!-- /RES -->
<h1 id="1-概述"><a href="#1-概述" class="headerlink" title="1. 概述"></a>1. 概述</h1><blockquote>
<p>14 章节：编写自己的输入输出运算符<br>17 章节：控制输入输出格式， 对文件进行随机访问</p>
</blockquote>
<ul>
<li>C++ 语言不直接处理输入输出，而通过 IO 库来处理 IO。</li>
<li>IO 库定义了读写<strong>内置类型</strong>值的操作。</li>
<li>其他类可定义类似的 IO 操作，来读写自己的对象。</li>
<li><p>这些类被分别定义于三个头文件之中：</p>
<ul>
<li>iostream 头文件中定义了读写<strong>普通流（控制台）</strong>的基本类型。  </li>
<li>fstream 头文件中的定义了读写<strong>命名文件</strong>的类型。</li>
<li>stringstream 头文件中定义了读写<strong>内存 string 对象</strong>的类型。</li>
</ul>
</li>
<li><p>IO 库类型概述：</p>
</li>
</ul>
<p><img src="/res/mdImg/IO操作类图.png" alt="IO操作类图"></p>
<table>
<thead>
<tr>
<th style="text-align:center">头文件</th>
<th style="text-align:center">类型</th>
<th style="text-align:center">类型（对于宽字符)</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>&lt;iostream&gt;</code></td>
<td style="text-align:center"><code>istream</code></td>
<td style="text-align:center"><code>wistream</code></td>
<td style="text-align:left">从流读取数据</td>
</tr>
<tr>
<td style="text-align:center">&nbsp;</td>
<td style="text-align:center"><code>ostream</code></td>
<td style="text-align:center"><code>wostream</code></td>
<td style="text-align:left">向流写入数据</td>
</tr>
<tr>
<td style="text-align:center">&nbsp;</td>
<td style="text-align:center"><code>iostream</code></td>
<td style="text-align:center"><code>wiostream</code></td>
<td style="text-align:left">读写流</td>
</tr>
<tr>
<td style="text-align:center"><code>&lt;fstream&gt;</code></td>
<td style="text-align:center"><code>ifstream</code></td>
<td style="text-align:center"><code>wifstream</code></td>
<td style="text-align:left">从文件读取数据</td>
</tr>
<tr>
<td style="text-align:center">&nbsp;</td>
<td style="text-align:center"><code>ofstream</code></td>
<td style="text-align:center"><code>wofstream</code></td>
<td style="text-align:left">向文件写入数据</td>
</tr>
<tr>
<td style="text-align:center">&nbsp;</td>
<td style="text-align:center"><code>fstream</code></td>
<td style="text-align:center"><code>wfstream</code></td>
<td style="text-align:left">读写文件</td>
</tr>
<tr>
<td style="text-align:center"><code>&lt;sstream&gt;</code></td>
<td style="text-align:center"><code>istringstream</code></td>
<td style="text-align:center"><code>wistringstream</code></td>
<td style="text-align:left">从 string 读取数据</td>
</tr>
<tr>
<td style="text-align:center">&nbsp;</td>
<td style="text-align:center"><code>ostringstream</code></td>
<td style="text-align:center"><code>wostringstream</code></td>
<td style="text-align:left">向 string 写入数据</td>
</tr>
<tr>
<td style="text-align:center">&nbsp;</td>
<td style="text-align:center"><code>stringstream</code></td>
<td style="text-align:center"><code>wstringstream</code></td>
<td style="text-align:left">读写 string</td>
</tr>
</tbody>
</table>
<ul>
<li><p>为了支持使用<strong>宽字符</strong>的语言，标准库定义了一组类型和对象，用于操作<code>wchar_t</code>宽字符类型。 宽字符版本的类型 / 函数的名字以<code>w</code>开头，宽字符版本类型和对象与其对应的普通 char 版本类型在同一文件中。</p>
<ul>
<li>eg：cin, cout, cerr 对象分别对应 wcin, wcout, wcerr 对象。</li>
<li>eg: <fstream> 中有 ifstream 和 wifstream 两个类。</fstream></li>
</ul>
</li>
<li><p>IO 类型之间关系：通过继承体系，使得可以用类似的方式使用这些类的对象。(eg: 可使用操作<code>cin</code>的方式，操作<code>istream</code>和<code>istringstream</code>类的对象)</p>
</li>
<li>类继承关系描述：（附件中有类继承关系图）<ul>
<li>ifstream，istringstream 继承自 istream。</li>
<li>ofstream，ostringstream 继承自 ostream。</li>
<li>iostream 多重继承了 istream，ostream。</li>
<li>fstream，stringstream 继承自 iostream。</li>
</ul>
</li>
</ul>
<h1 id="2-标准输入输出"><a href="#2-标准输入输出" class="headerlink" title="2. 标准输入输出"></a>2. 标准输入输出</h1><blockquote>
<p>需添加头文件：<code>#include &lt;iostream&gt;</code></p>
</blockquote>
<h2 id="2-1-类型"><a href="#2-1-类型" class="headerlink" title="2.1. 类型"></a>2.1. 类型</h2><ul>
<li><code>std::cin</code></li>
<li><code>std::cout</code></li>
<li><code>std::cerr</code></li>
<li><code>std::clog</code></li>
</ul>
<h2 id="2-2-操作符"><a href="#2-2-操作符" class="headerlink" title="2.2. 操作符"></a>2.2. 操作符</h2><ul>
<li><code>&lt;&lt;</code></li>
<li><code>&gt;&gt;</code></li>
<li><code>std::endl</code><ol>
<li>结束当前行</li>
<li>将与设备关联的缓冲区中内容刷新到设备</li>
</ol>
</li>
</ul>
<h1 id="3-iostream-头文件"><a href="#3-iostream-头文件" class="headerlink" title="3. iostream 头文件"></a>3. <code>iostream</code> 头文件</h1><h2 id="3-1-cin-cout-cerr"><a href="#3-1-cin-cout-cerr" class="headerlink" title="3.1. cin cout cerr"></a>3.1. <code>cin</code> <code>cout</code> <code>cerr</code></h2><ul>
<li><code>istream</code>类的<code>cin</code>对象：用于从标准输入读取数据。可使用<code>&gt;&gt;</code>和<code>getline()</code>.</li>
<li><code>ostream</code>类的以下对象：<ul>
<li><code>cout</code>对象：从标准输出输出数据。可使用<code>&lt;&lt;</code>.</li>
<li><code>cerr</code>对象：向标准错误输出数据。可使用<code>&lt;&lt;</code>.</li>
</ul>
</li>
</ul>
<h1 id="4-IO-库流特性"><a href="#4-IO-库流特性" class="headerlink" title="4. IO 库流特性"></a>4. IO 库<strong>流特性</strong></h1><ul>
<li>IO 库流特性可无差别的用于普通流，文件流，string 流，char 或 宽字符流中。</li>
</ul>
<h2 id="4-1-IO-对象的传递"><a href="#4-1-IO-对象的传递" class="headerlink" title="4.1. IO 对象的传递"></a>4.1. IO 对象的传递</h2><ul>
<li>只能使用 <strong>非 const 的指针或引用</strong> 传递。</li>
<li>原因：<ul>
<li>不可为<code>const</code>类型。因为读写 IO 对象都会改变其状态。</li>
<li>只能使用<strong>指针或引用</strong>传递。因为无法对 IO 对象进行<strong>拷贝</strong>或<strong>赋值</strong>。（函数<strong>形参</strong>和<strong>返回值</strong>类型不可为 IO 流类型）。</li>
</ul>
</li>
<li><p>代码</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 正确</span></span><br><span class="line"><span class="function">iostream &amp;<span class="title">func</span><span class="params">(iostream &amp;io, fstream *fs)</span> </span>&#123;&#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 错误</span></span><br><span class="line"><span class="function">iostream <span class="title">func</span><span class="params">(iostream io)</span> </span>&#123;&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="4-2-流的条件状态"><a href="#4-2-流的条件状态" class="headerlink" title="4.2. 流的条件状态"></a>4.2. 流的<strong>条件状态</strong></h2><ul>
<li><strong>任何一个</strong> IO 对象在<strong>任何时刻</strong>都对应一种状态。</li>
<li>作用：用于保存 IO 对象的状态。</li>
<li>产生的原因：IO 操作本身可能会发生错误，且有些错误发生在系统深处，应用程序无法对其修正。所以需要存储 IO 对象本身的状态，供程序访问和修改。</li>
<li><p>注意：</p>
<ul>
<li>因为只有当一个流处于无错误状态下，才能通过它进行正确的读写。</li>
<li>且对一个已出错的流进行后续 IO 操作，都会失败。</li>
<li><p>所以要在每次使用流之前，先检查该流的状态。</p>
<blockquote>
<p>cin 希望读取 int 型的值。当输入内容非 int 时（eg: 输入了 EOF 或一串字符串），cin 会处于错误状态（strm::filebit）。之后对 cin 的后续操作也会出错。</p>
</blockquote>
<figure class="highlight abnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">int a<span class="comment">;</span></span><br><span class="line">cin &gt;&gt; a<span class="comment">;</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<h3 id="4-2-1-条件状态"><a href="#4-2-1-条件状态" class="headerlink" title="4.2.1. 条件状态"></a>4.2.1. 条件状态</h3><blockquote>
<p>strm 表示 各个 IO 库类型（eg：istream， iostream）。</p>
</blockquote>
<ul>
<li>使用<code>strm::iostate</code>类型表示流对象的条件状态。本类型是<strong>机器相关类型</strong>。</li>
<li>该类型本质为一种<strong>位集合</strong>。其中有四种该类型的<code>constexpr</code>枚举值。可使用<strong>位运算符</strong>来同时操作多个位。</li>
<li>本类型枚举值：</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">位模式</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>strm::badbit</code></td>
<td style="text-align:left">流已崩溃（出现系统级错误，无法再使用时）</td>
</tr>
<tr>
<td style="text-align:center"><code>strm::failbit</code></td>
<td style="text-align:left">一个 IO 操作失败，修正后流仍可使用<br>（eg：希望读一个 int 却读到字符时）</td>
</tr>
<tr>
<td style="text-align:center"><code>strm::eofbit</code></td>
<td style="text-align:left">流到达了文件末尾，同时 filebit 也会置位</td>
</tr>
<tr>
<td style="text-align:center"><code>strm::goodbit</code></td>
<td style="text-align:left">流未处于错误状态，此值为 0</td>
</tr>
</tbody>
</table>
<h3 id="4-2-2-条件状态的操作函数"><a href="#4-2-2-条件状态的操作函数" class="headerlink" title="4.2.2. 条件状态的操作函数"></a>4.2.2. 条件状态的操作函数</h3><blockquote>
<p>s 表示一个流对象（eg: cin）<br>flags 类型为 strm::state。（eg: cin::badbit | cin::filebit）</p>
</blockquote>
<table>
<thead>
<tr>
<th style="text-align:center">函数</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>s.eof(): bool</code></td>
<td style="text-align:left">判断 s 流的<code>eofbit</code>是否置位</td>
</tr>
<tr>
<td style="text-align:center"><code>s.fail(): bool</code></td>
<td style="text-align:left">判断 s 流的<code>failbit</code>或<code>badbit</code>是否置位</td>
</tr>
<tr>
<td style="text-align:center"><code>s.bad(): bool</code></td>
<td style="text-align:left">判断 s 流的<code>badbit</code>是否置位</td>
</tr>
<tr>
<td style="text-align:center"><code>s.good(): bool</code></td>
<td style="text-align:left">判断 s 流是否处于有效状态</td>
</tr>
<tr>
<td style="text-align:center"><code>s.clear()</code></td>
<td style="text-align:left">将流 s 所有条件状态位复位，<br>并将流状态设为有效</td>
</tr>
<tr>
<td style="text-align:center"><code>s.clear(flags)</code></td>
<td style="text-align:left">将流对应的状态位复位</td>
</tr>
<tr>
<td style="text-align:center"><code>s.setstate(flags)</code></td>
<td style="text-align:left">将流对应的状态位置位</td>
</tr>
<tr>
<td style="text-align:center"><code>s.rdstate(): strm::iostate</code></td>
<td style="text-align:left">返回流 s 的当前条件状态</td>
</tr>
</tbody>
</table>
<h3 id="4-2-3-代码示例"><a href="#4-2-3-代码示例" class="headerlink" title="4.2.3. 代码示例"></a>4.2.3. 代码示例</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="keyword">char</span> myChar;</span><br><span class="line">    <span class="comment">// 先判断流是否有效，再执行后续 IO 操作。等价于：cin.good()</span></span><br><span class="line">    <span class="keyword">while</span> (<span class="built_in">cin</span> &gt;&gt; myChar) &#123;</span><br><span class="line">        <span class="comment">// ....</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// auto 类型为 cin::state</span></span><br><span class="line">    <span class="keyword">auto</span> oldState = <span class="built_in">cin</span>.rdstate();    <span class="comment">// 读取 cin 的状态</span></span><br><span class="line">    <span class="built_in">cin</span>.clear(<span class="built_in">cin</span>.failbit &amp; <span class="built_in">cin</span>.badbit);    <span class="comment">// 清除指定位</span></span><br><span class="line">    <span class="built_in">cin</span>.setState(oldState);            <span class="comment">// 设置状态</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 输出 0 1 2 4</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="built_in">std</span>::iostream::good &lt;&lt; <span class="built_in">std</span>::iostream::badbit</span><br><span class="line">        &lt;&lt; <span class="built_in">std</span>::iostream::eofbit &lt;&lt; <span class="built_in">std</span>::iostream::failbit &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="built_in">std</span>::iostream::iostate coutstate = <span class="built_in">cin</span>.rdstate(); <span class="comment">// 得到 cin 对象的原始状态值</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; coutstate &lt;&lt; <span class="built_in">endl</span>;  <span class="comment">// 输出 0 cin 的状态值是 std::iostream::good</span></span><br><span class="line"> </span><br><span class="line">    <span class="keyword">int</span> i;</span><br><span class="line">    <span class="built_in">cin</span> &gt;&gt; i; <span class="comment">// 输入"123"</span></span><br><span class="line">    <span class="comment">// 输出 0 因为“123”可以被正确转成 int 并被存入 i 所以 cin 的状态置为 std::iostream::good</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="built_in">cin</span>.rdstate() &lt;&lt; <span class="built_in">endl</span>; </span><br><span class="line">    <span class="comment">// 输出 1 0 0 0</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="built_in">cin</span>.good() &lt;&lt; <span class="built_in">cin</span>.eof() &lt;&lt; <span class="built_in">cin</span>.fail() &lt;&lt; <span class="built_in">cin</span>.bad() &lt;&lt; end;</span><br><span class="line"> </span><br><span class="line">    <span class="built_in">cin</span> &gt;&gt; i; <span class="comment">// 输入"abd"</span></span><br><span class="line">    <span class="comment">// 输出 4  因为“abc”无法转成 int 存入 i 所以 cin 的状态置为 std::iostream::failbit</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="built_in">cin</span>.rdstate() &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="comment">// 输出 0 0 1 0</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="built_in">cin</span>.good() &lt;&lt; <span class="built_in">cin</span>.eof() &lt;&lt; <span class="built_in">cin</span>.fail() &lt;&lt; <span class="built_in">cin</span>.bad() &lt;&lt; end;</span><br><span class="line"> </span><br><span class="line">    <span class="comment">// 重置 cin 状态为 std::iostream::good 否则下面的 cin &lt;&lt; i 不会执行</span></span><br><span class="line">    <span class="comment">// 使用其等效：cin.clear(std::iostream::failbit)</span></span><br><span class="line">    <span class="built_in">cin</span>.clear();</span><br><span class="line"> </span><br><span class="line">    <span class="built_in">cin</span> &gt;&gt; i; <span class="comment">// 输入"568"</span></span><br><span class="line">    <span class="comment">// 输出 0 因为“568”可以被正确转成 int 并被存入 i 所以 cin 的状态置为 std::iostream::good</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="built_in">cin</span>.rdstate() &lt;&lt; <span class="built_in">endl</span>;</span><br><span class="line">    <span class="comment">// 输出 1 0 0 0</span></span><br><span class="line">    <span class="built_in">cout</span> &lt;&lt; <span class="built_in">cin</span>.good() &lt;&lt; <span class="built_in">cin</span>.eof() &lt;&lt; <span class="built_in">cin</span>.fail() &lt;&lt; <span class="built_in">cin</span>.bad() &lt;&lt; end;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="4-3-缓冲区"><a href="#4-3-缓冲区" class="headerlink" title="4.3. 缓冲区"></a>4.3. 缓冲区</h2><ul>
<li>缓冲区也称为<strong>缓存</strong>，是内存空间的一部分。</li>
<li>作用：在输入输出设备与 CPU 之间，用来缓存数据。使得低速的 IO 设备与高速的 CPU 能够协调工作。</li>
</ul>
<h3 id="4-3-1-缓冲区的类型"><a href="#4-3-1-缓冲区的类型" class="headerlink" title="4.3.1. 缓冲区的类型"></a>4.3.1. 缓冲区的类型</h3><ul>
<li>根据与其相对应的设备是输入设备还是输出设备， 可分为两类：<ul>
<li>输入缓冲区</li>
<li>输出缓冲区</li>
</ul>
</li>
<li>根据缓冲区刷新， 可分为三类：<ul>
<li>全缓冲</li>
<li>行缓冲</li>
<li>不带缓冲</li>
</ul>
</li>
</ul>
<h4 id="4-3-1-1-全缓冲"><a href="#4-3-1-1-全缓冲" class="headerlink" title="4.3.1.1. 全缓冲"></a>4.3.1.1. 全缓冲</h4><ul>
<li>当填满缓冲区之后，才刷新缓冲区，执行真正 IO 操作。</li>
<li>典型代表：对磁盘文件的读取。</li>
<li><p>代码示例</p>
<blockquote>
<p>测试写入文件对应的是否为全缓冲<br>windows 全缓冲大小为 4K（4096 字节）。</p>
</blockquote>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">std</span>::<span class="function">ofstream <span class="title">outfile</span><span class="params">(<span class="string">"F:\\test.txt"</span>)</span></span>;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// windows 全缓存区大小为 4K(4096). 存储第 4097 字节时就会进行刷新全缓存区。</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">4096</span>; ++i) &#123;</span><br><span class="line">    outfile &lt;&lt; <span class="string">"a"</span>;     <span class="comment">// 添加 endl，flush 语句会刷新</span></span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">system(<span class="string">"PAUSE"</span>);    <span class="comment">// 按任意键继续</span></span><br><span class="line"> </span><br><span class="line">outfile &lt;&lt; <span class="string">"b"</span>;        <span class="comment">// 缓冲区满了，开始刷新</span></span><br><span class="line">system(<span class="string">"PAUSE"</span>);</span><br><span class="line"> </span><br><span class="line">outfile.close();    <span class="comment">// 关闭文件，会刷新</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="4-3-1-2-行缓冲"><a href="#4-3-1-2-行缓冲" class="headerlink" title="4.3.1.2. 行缓冲"></a>4.3.1.2. 行缓冲</h4><ul>
<li>在输入输出过程中，遇到<strong>换行符</strong>时，刷新缓冲区，执行真正 IO 操作。</li>
<li>典型代表：从键盘输入数据。输入的字符先存入缓冲区，等按下回车按键后，才真正读入数据。</li>
<li><p>代码示例</p>
<blockquote>
<ul>
<li>以通过 getchar() 读取 cin 为示例。证实 cin 并不是用户输入之后，在程序里就能立即得到的。</li>
<li>实验结果：例如用户输入了 iostream 回车 这一串，只有输入回车后，才能看到输出了 “a: i”</li>
</ul>
</blockquote>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 首次执行本函数，阻塞等待用户输入，并将用户输入内容保存到输入缓存区，直到输入 回车（回车也放入缓存区), 函数返回第一个输入的第一个字符。</span></span><br><span class="line"><span class="comment">// 之后执行本函数，只要缓存区中存在字符，就直接返回。直到将缓存区内容全部读取完成。</span></span><br><span class="line"><span class="keyword">char</span> a = getchar();</span><br><span class="line"><span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"a: "</span> &lt;&lt; a &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">while</span> (a = getchar()) &#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"while a: "</span> &lt;&lt; a &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="4-3-1-3-不带缓冲"><a href="#4-3-1-3-不带缓冲" class="headerlink" title="4.3.1.3. 不带缓冲"></a>4.3.1.3. 不带缓冲</h4><ul>
<li>不进行缓冲，程序的读写操作会直接引发真正的 IO 操作。</li>
<li>典型代表：stderr 的输出。以便错误信息可以尽快显示出来。</li>
<li><p>代码示例</p>
<blockquote>
<p>疑惑之处：将 cerr 替换为 cout 之后，在“输入任意字符”之前，也会有 ‘a’ 输出。不是此时应该还在缓冲区没有被刷新的吗 ？？？</p>
</blockquote>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">std</span>::<span class="built_in">cerr</span> &lt;&lt; <span class="string">"a"</span>;</span><br><span class="line">system(<span class="string">"PAUSE"</span>);</span><br><span class="line"><span class="built_in">std</span>::<span class="built_in">cerr</span> &lt;&lt; <span class="string">"b"</span>;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="4-3-2-缓冲区的刷新"><a href="#4-3-2-缓冲区的刷新" class="headerlink" title="4.3.2. 缓冲区的刷新"></a>4.3.2. 缓冲区的刷新</h3><ul>
<li>缓冲区的刷新时机如下：<ul>
<li>缓冲区已满，再向缓冲区写入数据时。</li>
<li>文件正常关闭时（程序正常退出时）(main 函数 return 操作时，会刷新输出缓冲)。</li>
<li><a href="#显式刷新缓冲区">显式刷新缓冲区</a>。</li>
<li><a href="#设置缓冲区是否立即刷新">设置缓冲区是否立即刷新</a>。</li>
<li><a href="#关联流">将输出流关联到另一个流</a>。一个输出流 A 关联到另一个流 B 时，读写流 B，都会使输出流 A 被刷新。</li>
</ul>
</li>
<li>注意：<ul>
<li>程序非正常退出，将不会刷新输出缓冲。</li>
</ul>
</li>
</ul>
<h4 id="4-3-2-1-显式刷新缓冲区"><a href="#4-3-2-1-显式刷新缓冲区" class="headerlink" title="4.3.2.1. 显式刷新缓冲区"></a>4.3.2.1. <span id="显式刷新缓冲区">显式刷新缓冲区</span></h4><ul>
<li>能进行显式刷新缓冲区的操作符：</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">操作符</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>endl</code>操作符</td>
<td style="text-align:left">插入一个换行符，并刷新缓冲区</td>
</tr>
<tr>
<td style="text-align:center"><code>ends</code>操作符</td>
<td style="text-align:left">插入一个空字符，并刷新缓冲区</td>
</tr>
<tr>
<td style="text-align:center"><code>flush</code>操作符</td>
<td style="text-align:left">直接刷新缓冲区</td>
</tr>
</tbody>
</table>
<ul>
<li>代码示例  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">"hehe"</span> &lt;&lt; <span class="built_in">endl</span>;    <span class="comment">// "hehe"换行</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">"hehe"</span> &lt;&lt; ends;    <span class="comment">// "hehe"空字符</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="string">"hehe"</span> &lt;&lt; flush;    <span class="comment">// "hehe"</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="4-3-2-2-设置缓冲区是否立即刷新"><a href="#4-3-2-2-设置缓冲区是否立即刷新" class="headerlink" title="4.3.2.2. 设置缓冲区是否立即刷新"></a>4.3.2.2. <span id="设置缓冲区是否立即刷新">设置缓冲区是否立即刷新</span></h4><ul>
<li>使用 <code>unitbuf</code> 操作符设置缓冲区在每次写入后都将刷新。</li>
<li>使用 <code>nounitbuf</code> 操作符设置缓冲区恢复正常的缓冲机制。</li>
<li><p>代码示例</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 设置之后，在每次输出操作后，都将立即刷新缓冲区</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; unitbuf;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="number">123</span>;    <span class="comment">// 立即刷新</span></span><br><span class="line"> </span><br><span class="line"><span class="comment">// 设置之后，恢复为正常的缓冲机制</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; nounitbuf;</span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; <span class="number">123</span>;    <span class="comment">// 使用正常的缓冲</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h4 id="4-3-2-3-将输出流关联到输入流"><a href="#4-3-2-3-将输出流关联到输入流" class="headerlink" title="4.3.2.3. 将输出流关联到输入流"></a>4.3.2.3. <span id="关联流">将输出流关联到输入流</span></h4><ul>
<li>将一个<strong>输出流</strong>（A）关联到另一个流（可为输入或输出流）（B，C，D）。</li>
<li>作用：用于简化输出流（A）的刷新。</li>
<li>本流（B）只能设置一个关联的输出流（A）。 但一个输出流（A）可关联到多个流（B，C，D）。</li>
<li>操作：使用函数<code>tie()</code>其有两个重载：<ol>
<li>不带参数，返回本对象当前关联到的输出流指针。若无，则返回空指针。</li>
<li>接受一个指向<code>ostream</code>的指针，将本对象关联到该输出流。返回值同上。</li>
</ol>
</li>
<li>默认情况下，<code>cout</code>会关联到<code>cin</code>和<code>cerr</code>，则读<code>cin</code>或写<code>cerr</code>都会使<code>cout</code>流刷新。</li>
<li>代码  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//cout 关联到 cin （仅作为展示。原本就已关联)</span></span><br><span class="line"><span class="built_in">cin</span>.tie(&amp;<span class="built_in">cout</span>);   </span><br><span class="line"> </span><br><span class="line"><span class="comment">//cin 不与其他流关联，并返回之前关联的输出流（如果有的话)</span></span><br><span class="line">ostream * oldTie = <span class="built_in">cin</span>.tie(<span class="literal">nullptr</span>);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="5-文件读取类"><a href="#5-文件读取类" class="headerlink" title="5. 文件读取类"></a>5. 文件读取类</h1><ul>
<li>头文件<code>&lt;fstream&gt;</code>中有三个类：<code>ifstream</code>，<code>ofstream</code>，<code>fstream</code>。分别继承自<code>istream</code>， <code>ostream</code>，<code>iostream</code>。因此可使用父类全部功能。</li>
<li>注意：当一个 fstream 对象被销毁时，将会自动 close 该文件。</li>
</ul>
<h2 id="5-1-打开文件"><a href="#5-1-打开文件" class="headerlink" title="5.1. 打开文件"></a>5.1. 打开文件</h2><ul>
<li>可使用 <code>open()</code>函数</li>
<li>也可直接使用文件读取类的构造函数完成（参数与 open() 函数一致）。</li>
<li><p><code>open()</code>函数原型</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//filename: 要打开的文件名</span></span><br><span class="line"><span class="comment">//mode: 打开文件的方式</span></span><br><span class="line"><span class="comment">//access: 待打开文件的属性</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">open</span><span class="params">(<span class="keyword">const</span> <span class="keyword">char</span> *filename, <span class="keyword">int</span> mode, <span class="keyword">int</span> access)</span></span>;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="5-1-1-打开文件的方式"><a href="#5-1-1-打开文件的方式" class="headerlink" title="5.1.1. 打开文件的方式"></a>5.1.1. 打开文件的方式</h3><ul>
<li>在类 <code>ios</code>（所有流式 IO 类的基类）中定义。可使用<code>|</code>运算符将多值组合使用。<blockquote>
<p>『问题 Q]： ios::nocreate 和 ios::noreplace 在 VS 的参数自动完成中为：ios::_Nocreate 和 ios::_Noreplace。这到底是哪个正确？？？</p>
</blockquote>
</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">值</th>
<th style="text-align:center">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>ios::in</code></td>
<td style="text-align:center">以输入方式打开</td>
</tr>
<tr>
<td style="text-align:center"><code>ios::out</code></td>
<td style="text-align:center">以输出方式打开（文件不存在则创建）</td>
</tr>
<tr>
<td style="text-align:center"><code>ios::app</code></td>
<td style="text-align:center">以追加的方式打开文件（文件写指针在文件结尾）</td>
</tr>
<tr>
<td style="text-align:center"><code>ios::ate</code></td>
<td style="text-align:center">文件打开后定位到文件结尾（app 内包含此项）</td>
</tr>
<tr>
<td style="text-align:center"><code>ios::trunc</code></td>
<td style="text-align:center">打开并截断文件</td>
</tr>
<tr>
<td style="text-align:center"><code>ios::binary</code></td>
<td style="text-align:center">以二进制方式打开文件『默认为文本方式』</td>
</tr>
<tr>
<td style="text-align:center"><code>ios::nocreate</code></td>
<td style="text-align:center">不创建文件（文件不存在时打开失败）</td>
</tr>
<tr>
<td style="text-align:center"><code>ios::noreplace</code></td>
<td style="text-align:center">不覆盖文件（打开文件时若文件已存在则失败）</td>
</tr>
</tbody>
</table>
<ul>
<li>说明<ul>
<li><code>in</code>模式只可用于<code>ifstream</code>和<code>fstream</code>对象。</li>
<li><code>out</code>模式只可用于<code>ofstream</code>和<code>fstream</code>对象。默认情况下，即使未指定<code>trunc</code>, 打开的文件也会被截断。若想文件不被截断，需同时指定<code>app</code>或同时指定<code>in</code>以既可读又可写的方式打开。</li>
<li><code>trunc</code>只有在<code>out</code>模式下才能被设置。</li>
<li><code>app</code>只有在<code>trunc</code>未被设置的情况下，才能被设置。当<code>app</code>设置后，即使<code>out</code>未设置，也是以写方式打开。</li>
<li><code>ate</code>和<code>binary</code>可用于任何类型的文件流对象。且可与其他模式任意配合使用。</li>
</ul>
</li>
<li>默认打开方式：当未指定文件打开模式时，会使用默认模式打开文件。<ul>
<li>与<code>ifstream</code>关联的文件默认以<code>in</code>模式打开。</li>
<li>与<code>ofstream</code>关联的文件默认以<code>out</code>模式打开。</li>
<li>与<code>fstream</code>关联的文件默认以<code>in</code>和<code>out</code>模式打开。</li>
</ul>
</li>
</ul>
<h3 id="5-1-2-待打开文件的属性"><a href="#5-1-2-待打开文件的属性" class="headerlink" title="5.1.2. 待打开文件的属性"></a>5.1.2. 待打开文件的属性</h3><ul>
<li>可使用 <code>|</code> 或 <code>+</code> 将多值组合使用。<blockquote>
<p>『问题 Q]： 在 VS 中，可查看到该参数的默认值为 64。这是怎么组合得到的？ 难道 C++11 对该部分作了修改？？?<br>一般不使用。直接使用默认形参就行。</p>
</blockquote>
</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">值</th>
<th style="text-align:center">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">0</td>
<td style="text-align:center">普通文件，打开访问</td>
</tr>
<tr>
<td style="text-align:center">1</td>
<td style="text-align:center">只读文件</td>
</tr>
<tr>
<td style="text-align:center">2</td>
<td style="text-align:center">隐含文件</td>
</tr>
<tr>
<td style="text-align:center">4</td>
<td style="text-align:center">系统文件</td>
</tr>
</tbody>
</table>
<h3 id="5-1-3-代码示例"><a href="#5-1-3-代码示例" class="headerlink" title="5.1.3. 代码示例"></a>5.1.3. 代码示例</h3><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;fstream&gt;</span></span></span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">std</span>::fstream file;</span><br><span class="line">    file.open(<span class="string">"E:\\test.txt"</span>, <span class="built_in">std</span>::ios::out | <span class="built_in">std</span>::ios::app);</span><br><span class="line">    <span class="comment">// 等价于</span></span><br><span class="line">    <span class="comment">// std::fstream file("E:\\test.txt", std::ios::out | std::ios::app);</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="5-2-关闭文件"><a href="#5-2-关闭文件" class="headerlink" title="5.2. 关闭文件"></a>5.2. 关闭文件</h2><ul>
<li>使用 <code>close()</code> 关闭文件。</li>
</ul>
<h2 id="5-3-读写文件"><a href="#5-3-读写文件" class="headerlink" title="5.3. 读写文件"></a>5.3. 读写文件</h2><ul>
<li>读写文件可分为 <strong>对二进制文件读写</strong> 和 <strong>对文本文件读写</strong>。</li>
<li>对文本文件读写，可直接使用 <code>&gt;&gt;</code> 和 <code>&lt;&lt;</code>。</li>
<li>对二进制文件读写，使用 <code>&gt;&gt;</code> 和 <code>&lt;&lt;</code> 无意义。</li>
</ul>
<h3 id="5-3-1-读写文本文件"><a href="#5-3-1-读写文本文件" class="headerlink" title="5.3.1. 读写文本文件"></a>5.3.1. 读写文本文件</h3><ul>
<li>使用 <code>&gt;&gt;</code> 读取数据。</li>
<li>使用 <code>&lt;&lt;</code> 写出数据。</li>
<li>本方式有一定的数据格式化能力：使用以下操作符</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">操作符</th>
<th style="text-align:center">说明</th>
<th style="text-align:center">输入或输出</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>hex</code></td>
<td style="text-align:center">格式化为<strong>十六进制</strong>数值数据</td>
<td style="text-align:center">输入输出</td>
</tr>
<tr>
<td style="text-align:center"><code>oct</code></td>
<td style="text-align:center">格式化为<strong>八进制</strong>数值数据</td>
<td style="text-align:center">输入输出</td>
</tr>
<tr>
<td style="text-align:center"><code>dec</code></td>
<td style="text-align:center">格式化为<strong>十进制</strong>数值数据</td>
<td style="text-align:center">输入输出</td>
</tr>
<tr>
<td style="text-align:center"><code>endl</code></td>
<td style="text-align:center">输出一个换行符，并刷新缓冲区</td>
<td style="text-align:center">输出</td>
</tr>
<tr>
<td style="text-align:center"><code>ends</code></td>
<td style="text-align:center">输出一个空字符</td>
<td style="text-align:center">输出</td>
</tr>
</tbody>
</table>
<ul>
<li><p>使用示例</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">fstream <span class="title">file</span><span class="params">(<span class="string">"test.txt"</span>, ios::in|ios::out)</span></span>;</span><br><span class="line"> </span><br><span class="line">file &lt;&lt; hex &lt;&lt; <span class="number">15</span>;    <span class="comment">// 把 123 以十六进制方式输出： f</span></span><br></pre></td></tr></table></figure>
</li>
</ul>
<h3 id="5-3-2-读写二进制文件"><a href="#5-3-2-读写二进制文件" class="headerlink" title="5.3.2. 读写二进制文件"></a>5.3.2. 读写二进制文件</h3><ul>
<li><p>使用 <code>put()</code> 写一个字符</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">ofstream &amp;<span class="title">put</span><span class="params">(<span class="keyword">char</span> ch)</span></span>;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li><p>使用 <code>get()</code> 读</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 从流中读取一个字符，存于 ch. 若读到文件结尾，返回空字符。</span></span><br><span class="line"><span class="function">ifstream &amp;<span class="title">get</span><span class="params">(<span class="keyword">char</span> &amp;ch)</span></span>;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 从流中返回一个字符。若达到文件结尾，返回 EOF</span></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">get</span><span class="params">()</span></span>;</span><br><span class="line"> </span><br><span class="line"><span class="comment">// 把字符读入到 buf 中。直到读入了 num 个字符或读到 delim 指定的字符后返回。</span></span><br><span class="line"><span class="function">ifstream &amp;<span class="title">get</span><span class="params">(<span class="keyword">char</span> *buf, <span class="keyword">int</span> num, <span class="keyword">char</span> delim=<span class="string">'\n'</span>)</span></span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>读写数据块</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">read(<span class="keyword">unsigned</span> <span class="keyword">char</span> *buf, <span class="keyword">int</span> num);</span><br><span class="line">write(<span class="keyword">const</span> <span class="keyword">unsigned</span> <span class="keyword">char</span> *buf, <span class="keyword">int</span> num);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h2 id="5-4-检测"><a href="#5-4-检测" class="headerlink" title="5.4. 检测"></a>5.4. 检测</h2><ul>
<li>检测文件是否已打开： <code>bool is_open() const;</code></li>
<li>检测是否达到文件末尾： <code>int eof();</code> 达到末尾返回<strong>非零值</strong>，否则返回 0。</li>
</ul>
<h2 id="5-5-流指针"><a href="#5-5-流指针" class="headerlink" title="5.5. 流指针"></a>5.5. 流指针</h2><ul>
<li>C++ 通过维护<strong>流指针</strong>来对流的读写位置进行控制。</li>
<li>每次执行输入或输出后，对应指针会<strong>自动</strong>变化。</li>
<li>读指针：get pointer，指向下一个被读取的元素。</li>
<li>写指针：put pointer，指向下一个元素的位置。</li>
<li>ifstream，istream 有读指针。</li>
<li>ofstream，ostream 有写指针。</li>
<li><p>fstream，iostream 既有读指针，又有写指针。</p>
</li>
<li><p>指针位置类型为 pos_type。（是一个整数）。</p>
</li>
<li>获取指针位置<ul>
<li><code>tellg()</code>：获取读指针位置。</li>
<li><code>tellp()</code>：获取写指针位置。</li>
</ul>
</li>
<li>设置指针位置。有两种重载。</li>
<li><p>对于 文本文件 只是用第一种重载。且 opsition 就是 获取到的指针位置，而不能对其进行修改。</p>
<ul>
<li>因为流指针的值对于文本文件和二进制文件的计算方法不同。为了防止文本文件中某些特殊字符被修改。</li>
</ul>
</li>
<li><p>第一种重载。从文件开头开始计算位置。</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">seekg(pos_type position);</span><br><span class="line">seekp(pos_type position);</span><br></pre></td></tr></table></figure>
</li>
<li><p>第二种重载。可指定偏移量的计算位置。</p>
<blockquote>
<ul>
<li>offset 为偏移的基准点，可取以下值：<ul>
<li>ios::beg 流开始位置</li>
<li>ios::cur 流当前位置</li>
<li>ios::end 流末尾位置</li>
</ul>
</li>
</ul>
</blockquote>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">seekg(off_type offset, seekdir direction);</span><br><span class="line">seekp(off_type offset, seekdir direction);</span><br></pre></td></tr></table></figure>
</li>
</ul>
<ul>
<li><p>代码示例</p>
  <figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    <span class="built_in">std</span>::<span class="function">ifstream <span class="title">file</span><span class="params">(<span class="string">"F:\\test.txt"</span>, <span class="built_in">std</span>::ios::in | <span class="built_in">std</span>::ios::binary)</span></span>;</span><br><span class="line">    <span class="keyword">long</span> start, end;</span><br><span class="line">    start = file.tellg();    <span class="comment">// 获取文件开头位置</span></span><br><span class="line"> </span><br><span class="line">    file.seekg(<span class="number">0</span>, <span class="built_in">std</span>::ios::end);    <span class="comment">// 移动读指针到文件末尾</span></span><br><span class="line">    end = file.tellg();        <span class="comment">// 获取文件结尾位置</span></span><br><span class="line">    file.close();</span><br><span class="line">    <span class="built_in">std</span>::<span class="built_in">cout</span> &lt;&lt; <span class="string">"size: (bytes)"</span> &lt;&lt; end - start &lt;&lt; <span class="built_in">std</span>::<span class="built_in">endl</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<h1 id="6-sstream-头文件"><a href="#6-sstream-头文件" class="headerlink" title="6. sstream 头文件"></a>6. <code>sstream</code> 头文件</h1><ul>
<li><p>头文件<code>&lt;sstream&gt;</code>定义了<code>istringstream</code>, <code>ostringstream</code>, <code>stringstream</code>, 分别从 string 中读取数据，写入数据，读写数据。</p>
</li>
<li><p>以下介绍这些类中特有的功能：</p>
<blockquote>
<p><code>sstream</code>是头文件`<sstream>中定义的一个类型。</sstream></p>
</blockquote>
</li>
</ul>
<table>
<thead>
<tr>
<th style="text-align:center">方法</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>sstream::str()</code></td>
<td style="text-align:left">返回本对象中字符串的拷贝</td>
</tr>
<tr>
<td style="text-align:center"><code>sstream::str(s)</code></td>
<td style="text-align:left">将字符串 s 拷贝到本对象中</td>
</tr>
</tbody>
</table>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    zhaoyongCNSX
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://zhaoyongcnsx.github.io/2018/09/22/我的文档/" title="我的文档">https://zhaoyongcnsx.github.io/2018/09/22/我的文档/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/hello/" rel="tag"># hello</a>
          
            <a href="/tags/test/" rel="tag"># test</a>
          
            <a href="/tags/abc/" rel="tag"># abc</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/06/Hexo 搭建静态博客/" rel="next" title="">
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/logo.png"
                alt="zhaoyongCNSX" />
            
              <p class="site-author-name" itemprop="name">zhaoyongCNSX</p>
              <p class="site-description motion-element" itemprop="description">zhaoyongCNSX 的个人博客</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">2</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/zhaoyongCNSX" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:zhaoyongCNSX@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          
            <div class="cc-license motion-element" itemprop="license">
              <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" target="_blank">
                <img src="/images/cc-by-nc-sa.svg" alt="Creative Commons" />
              </a>
            </div>
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-概述"><span class="nav-text">1. 概述</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-标准输入输出"><span class="nav-text">2. 标准输入输出</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-类型"><span class="nav-text">2.1. 类型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-操作符"><span class="nav-text">2.2. 操作符</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-iostream-头文件"><span class="nav-text">3. iostream 头文件</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-cin-cout-cerr"><span class="nav-text">3.1. cin cout cerr</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-IO-库流特性"><span class="nav-text">4. IO 库流特性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-IO-对象的传递"><span class="nav-text">4.1. IO 对象的传递</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-流的条件状态"><span class="nav-text">4.2. 流的条件状态</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-1-条件状态"><span class="nav-text">4.2.1. 条件状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-2-条件状态的操作函数"><span class="nav-text">4.2.2. 条件状态的操作函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-2-3-代码示例"><span class="nav-text">4.2.3. 代码示例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-缓冲区"><span class="nav-text">4.3. 缓冲区</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-1-缓冲区的类型"><span class="nav-text">4.3.1. 缓冲区的类型</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-1-1-全缓冲"><span class="nav-text">4.3.1.1. 全缓冲</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-1-2-行缓冲"><span class="nav-text">4.3.1.2. 行缓冲</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-1-3-不带缓冲"><span class="nav-text">4.3.1.3. 不带缓冲</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-3-2-缓冲区的刷新"><span class="nav-text">4.3.2. 缓冲区的刷新</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-2-1-显式刷新缓冲区"><span class="nav-text">4.3.2.1. 显式刷新缓冲区</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-2-2-设置缓冲区是否立即刷新"><span class="nav-text">4.3.2.2. 设置缓冲区是否立即刷新</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-3-2-3-将输出流关联到输入流"><span class="nav-text">4.3.2.3. 将输出流关联到输入流</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-文件读取类"><span class="nav-text">5. 文件读取类</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#5-1-打开文件"><span class="nav-text">5.1. 打开文件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-1-打开文件的方式"><span class="nav-text">5.1.1. 打开文件的方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-2-待打开文件的属性"><span class="nav-text">5.1.2. 待打开文件的属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-1-3-代码示例"><span class="nav-text">5.1.3. 代码示例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-2-关闭文件"><span class="nav-text">5.2. 关闭文件</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-3-读写文件"><span class="nav-text">5.3. 读写文件</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-1-读写文本文件"><span class="nav-text">5.3.1. 读写文本文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-3-2-读写二进制文件"><span class="nav-text">5.3.2. 读写二进制文件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-4-检测"><span class="nav-text">5.4. 检测</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-5-流指针"><span class="nav-text">5.5. 流指针</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-sstream-头文件"><span class="nav-text">6. sstream 头文件</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zhaoyongCNSX</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">7.3k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  





  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/canvas_sphere.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'zhaoyongCNSX@163.com',
            repo: 'blogs',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: 'b00a50e88366c64af5b8772b1206047aa7b3ec3b',
            
                client_id: 'cc6ed49c5b86432240d3'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("TDDsUDe2bNJ9AuDLtdMqfUNo-gzGzoHsz", "0RHypA7igWU0QbMnfRg9D6DU");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
